package com.oriole.admin.controller;

import com.oriole.admin.feign.ISysConfigService;
import com.oriole.admin.feign.ISysMenuService;
import com.oriole.admin.feign.ISysUserService;
import com.oriole.admin.utils.SecurityUtils;
import com.oriole.common.annotation.OperationLog;
import com.oriole.common.constant.Constants;
import com.oriole.common.enums.BusinessType;
import com.oriole.common.util.VerifyCodeImageUtil;
import com.oriole.entity.sys.SysMenu;
import com.oriole.entity.vo.SysConfigVo;
import com.oriole.entity.vo.SysMenuVo;
import com.oriole.entity.vo.SysUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/3 21:36
 * description:
 */
@Api(tags = {"系统入口Controller"})
@Controller
public class IndexController {

    private static final Logger log = LoggerFactory.getLogger(IndexController.class);

    @Resource
    private ISysMenuService sysMenuService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysConfigService sysConfigService;

    private List<SysMenuVo> getSysMenuVos(List<SysMenu> menus) {
        List<SysMenuVo> sysMenuVos = new ArrayList<>();
        menus.forEach(menu -> {
            SysMenuVo sysMenuVo = new SysMenuVo();
            sysMenuVo.setId(menu.getId());
            sysMenuVo.setName(menu.getName());
            sysMenuVo.setUrl(menu.getUrl());
            sysMenuVo.setSort(menu.getSort());
            sysMenuVo.setParentId(menu.getParentId());
            sysMenuVos.add(sysMenuVo);
        });
        // 一级菜单
        List<SysMenuVo> firstNode = sysMenuVos.stream()
                .filter(menuVo -> Constants.GOD.equals(menuVo.getParentId()))
                .collect(Collectors.toList());
        // 二级菜单
        List<SysMenuVo> secondNode = sysMenuVos.stream()
                .filter(menuVo -> !Constants.GOD.equals(menuVo.getParentId()))
                .collect(Collectors.toList());
        firstNode.forEach(item -> {
            List<SysMenuVo> nodes = item.getChildren();
            for (SysMenuVo menuVo : secondNode) {
                if (menuVo.getParentId().equals(item.getId())) {
                    nodes.add(menuVo);
                }
            }
        });
        return firstNode;
    }

    @OperationLog(title = "系统Home-首页", businessType = BusinessType.TO_PAGE)
    @ApiOperation(value = "系统Home-首页")
    @GetMapping({"", "index"})
    public ModelAndView index() {
        Long userId = SecurityUtils.getUserId();
        // 左侧菜单
        List<SysMenu> sysMenus = sysMenuService.findByUserId(userId).getData();
        List<SysMenuVo> sysMenuVos = getSysMenuVos(sysMenus);
        // 快捷菜单
        List<SysMenu> sysShortcutMenus = sysMenuService.findShortcutByUserId(userId).getData();
        List<SysMenuVo> shortcutMenuVos = getSysMenuVos(sysShortcutMenus);
        // 用户基本信息
        SysUserVo sysUserVo = sysUserService.findSysUserVoById(userId).getData();
        // 系统基本配置
        SysConfigVo sysConfigVo = sysConfigService.findSysConfigVo().getData();

        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("sysMenuVos", sysMenuVos);
        modelAndView.addObject("shortcutMenuVos", shortcutMenuVos);
        modelAndView.addObject("sysUserVo", sysUserVo);
        modelAndView.addObject("sysConfigVo", sysConfigVo);
        return modelAndView;
    }

    @ApiOperation(value = "跳转到登录页")
    @GetMapping("/loginPage")
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    @ApiOperation(value = "获取验证码")
    @GetMapping("/getVerifyCodeImage")
    public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.getOutputStream();
        String verifyCode = VerifyCodeImageUtil.generateTextCode(VerifyCodeImageUtil.TYPE_NUM_UPPER, 4, null);
        //将验证码放到HttpSession里面
        request.getSession().setAttribute(Constants.SESSION_KEY_VERIFYCODE, verifyCode);
        log.info("verifyCode is {}", verifyCode);
        //设置输出的内容的类型为JPEG图像
        response.setContentType("image/jpeg");
        BufferedImage bufferedImage = VerifyCodeImageUtil.generateImageCode(verifyCode, 90, 30, 3, true, Color.WHITE, Color.BLACK, null);
        //写给浏览器
        ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());
    }

}
